package cn.innosmart.aq.reminder;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import cn.innosmart.aq.bean.Reminder;
import cn.innosmart.aq.util.SharedUtil;

/**
 * Created by David on 2016/1/18.
 */
public class ReminderManager extends BroadcastReceiver {

    public static final String TITLE = "title";
    public static final String TIME_HOUR = "timeHour";
    public static final String TIME_MINUTE = "timeMinute";
    public static final String CONTENT = "content";
    public static final String ID = "id";
    public static final String PENDINITENT = "pendinitent";

    /**
     * 创建备忘提醒的pendingIntent
     *
     * @param context
     * @param reminder 要保存的备忘日志
     * @param idExtra  id号 备忘日志的ID
     * @return
     */
    private static PendingIntent createPendingIntent(Context context, Reminder reminder, int idExtra) {
        Intent intent = new Intent(context, ReminderService.class);
        intent.putExtra(TITLE, reminder.title);
        intent.putExtra(TIME_HOUR, reminder.hour);
        intent.putExtra(TIME_MINUTE, reminder.minitue);
        intent.putExtra(CONTENT, reminder.content);
        intent.putExtra(ID, reminder.id);
        intent.putExtra(PENDINITENT, reminder.id * 100000 + idExtra);
        return PendingIntent.getService(context, reminder.id * 100000 + idExtra, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private static PendingIntent createPendingIntent(Context context, Reminder reminder) {
        Intent intent = new Intent(context, ReminderService.class);
        intent.putExtra(TITLE, reminder.title);
        intent.putExtra(TIME_HOUR, reminder.hour);
        intent.putExtra(TIME_MINUTE, reminder.minitue);
        intent.putExtra(CONTENT, reminder.content);
        intent.putExtra(ID, reminder.id);
        return PendingIntent.getService(context, reminder.id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    /**
     * 取消所有的闹钟
     *
     * @param context
     */
    public static void cancelAlarms(Context context) {
        ArrayList<Reminder> reminders = SharedUtil.getInstance().queryAllReminder();
        if (reminders != null) {
            for (Reminder reminder : reminders) {
                if (reminder.isEnable) {
                    if (reminder.repeat == Reminder.EVERYPERIODICDAY) {
                        PendingIntent pIntent = createPendingIntent(context, reminder, 7);
                        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                        alarmManager.cancel(pIntent);
                    } else if (reminder.repeat == Reminder.EVERYOERIODICWEEK) {
                        Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                        /**
                         * 每周的闹钟，需要循环遍历设置
                         */
                        while (iterator.hasNext()) {
                            Map.Entry entry = (Map.Entry) iterator.next();
                            int extraId = (int) entry.getKey();
                            PendingIntent pIntent = createPendingIntent(context, reminder, extraId);
                            alarmManager.cancel(pIntent);
                        }
                    } else if (reminder.repeat == Reminder.NERVER) {
                        PendingIntent pIntent = createPendingIntent(context, reminder, 8);
                        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                        alarmManager.cancel(pIntent);
                    }
                }
            }
        }
    }

    public static void cancelAlarm(Context context, Reminder reminder) {
        System.out.println("Cancel Alarm");
        if (reminder.repeat == Reminder.EVERYPERIODICDAY) {
            PendingIntent pIntent = createPendingIntent(context, reminder, 7);
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pIntent);
        } else if (reminder.repeat == Reminder.EVERYOERIODICWEEK) {
            Iterator iterator = reminder.repeatDatas.entrySet().iterator();
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                int extraId = (int) entry.getKey();
                PendingIntent pIntent = createPendingIntent(context, reminder, extraId);
                alarmManager.cancel(pIntent);
            }
        } else if (reminder.repeat == Reminder.NERVER) {
            PendingIntent pIntent = createPendingIntent(context, reminder, 8);
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pIntent);
        }
    }

    public static void setAlarms(Context context) {
        cancelAlarms(context);
        ArrayList<Reminder> reminders = SharedUtil.getInstance().queryAllReminder();
        for (Reminder reminder : reminders) {
            if (reminder.isEnable) {
                createAlarm(context, reminder);
            }
        }
    }

    /**
     * 创建闹钟
     *
     * @param context
     * @param reminder
     */
    public static void createAlarm(Context context, Reminder reminder) {
        System.out.println("Create Alarm");
        if (reminder.repeat == Reminder.EVERYPERIODICDAY) {
            long periodic = reminder.repeatDatas.get(7).longValue();
            int datperiodic = (int) (periodic / 1000 / 60 / 60 / 24);
            System.out.println("datepe=" + datperiodic);
            PendingIntent pIntent = createPendingIntent(context, reminder, 7);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, reminder.year);
            calendar.set(Calendar.MONTH, reminder.month);
            calendar.set(Calendar.DAY_OF_MONTH, reminder.day);
            calendar.set(Calendar.HOUR_OF_DAY, reminder.hour);
            calendar.set(Calendar.MINUTE, reminder.minitue);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            while (calendar.getTimeInMillis() < System.currentTimeMillis()) {
                calendar.add(Calendar.DAY_OF_YEAR, datperiodic);
            }
            setAlarm(context, calendar, pIntent, periodic);
        } else if (reminder.repeat == Reminder.EVERYOERIODICWEEK) {
//            while ()
            //MON	TUE	WED	THU	FRI	SAT	SUN
            Iterator iterator = reminder.repeatDatas.entrySet().iterator();
            while (iterator.hasNext()) {
                Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
                calendar.set(Calendar.YEAR, reminder.year);
                calendar.set(Calendar.MONTH, reminder.month);
                calendar.set(Calendar.DAY_OF_MONTH, reminder.day);
                calendar.set(Calendar.HOUR_OF_DAY, reminder.hour);
                calendar.set(Calendar.MINUTE, reminder.minitue);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                Map.Entry entry = (Map.Entry) iterator.next();
                int key = (int) entry.getKey();
                PendingIntent pIntent = createPendingIntent(context, reminder, key);
                long periodic = reminder.repeatDatas.get(key).longValue();
                int datperiodic = (int) (periodic / 1000 / 60 / 60 / 24);
                if (key < week) {
                    calendar.add(Calendar.DAY_OF_YEAR, 7 + week - key);
                } else if (key == week) {
                    if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
                        calendar.add(Calendar.DAY_OF_YEAR, datperiodic);
                    }
                } else if (key > week) {
                    calendar.add(Calendar.DAY_OF_YEAR, key - week);
                }
                setAlarm(context, calendar, pIntent, periodic);
            }
        } else if (reminder.repeat == Reminder.NERVER) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, reminder.year);
            calendar.set(Calendar.MONTH, reminder.month);
            calendar.set(Calendar.DAY_OF_MONTH, reminder.day);
            calendar.set(Calendar.HOUR_OF_DAY, reminder.hour);
            calendar.set(Calendar.MINUTE, reminder.minitue);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
                //忽略
                System.out.println("走到忽略里面了");
            } else {
                PendingIntent pIntent = createPendingIntent(context, reminder, 8);
                setAlarm(context, calendar, pIntent);
            }
        }
    }

    /**
     * 设置闹钟
     * @param context
     * @param calendar
     * @param sender
     */
    private static void setAlarm(Context context, Calendar calendar, PendingIntent sender) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
    }

    /**
     *  * 设置闹钟
     * @param context
     * @param calendar
     * @param sender
     * @param periodic
     */
    private static void setAlarm(Context context, Calendar calendar, PendingIntent sender, long periodic) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), periodic, sender);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        setAlarms(context);
    }
}
